package middlewares

import (
    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/gin"
    "hitme/go-api/logic/global"
    "hitme/go-api/modules/response"
    "net/http"
    "strconv"
)

// JWTAuth 中间件，检查token
func JWTAuth() gin.HandlerFunc {
    return func(context *gin.Context) {
        auth := context.Request.Header.Get("Authorization")
        if len(auth) == 0 {
            context.Abort()
            response.Err(context, http.StatusBadRequest, -1, "无权限访问")
        } else {
            // 校验token
            claim, err := parseToken(auth)
            //_, err := parseToken(auth)
            if err != nil {
                context.Abort()
                response.Err(context, http.StatusBadRequest, -1, "token 过期")
            } else {
                // 初始化参数
                userId, _ := strconv.Atoi(claim.Id)
                global.UserId = uint64(userId)
                global.Token = auth

                context.Next()
            }
        }
    }
}

func parseToken(token string) (*jwt.StandardClaims, error) {
    jwtToken, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(token *jwt.Token) (i interface{}, e error) {
        //return []byte(global.Settings.JwtInfo.SignKey), nil
        return nil, nil
    })
    if err == nil && jwtToken != nil {
        if claim, ok := jwtToken.Claims.(*jwt.StandardClaims); ok && jwtToken.Valid {
            return claim, nil
        }
    }
    return nil, err
}